import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:photo_pipeline/photo_pipeline.dart';
import 'package:photo_pipeline_default_bootstrap/photo_pipeline_default_bootstrap.dart';

import 'constants/colors.dart';
import 'constants/text_styles.dart';
import 'providers/pipeline_providers.dart';
import 'screens/home_screen.dart';
import 'screens/ai_pick_settings_screen.dart';
import 'screens/upload_tasks_screen.dart';

const bool enableCustomOverrides = false;

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();

  final bootstrapConfig =
      enableCustomOverrides ? _buildCustomBootstrapConfig() : null;

  final bootstrapResult =
      await PhotoPipelineBootstrap.run(config: bootstrapConfig);

  if (!bootstrapResult.isSuccess) {
    debugPrint('[PhotoPipeline] Bootstrap failed:');
    for (final error in bootstrapResult.errors) {
      debugPrint(' - ${error.code}: ${error.message}');
    }
    return;
  }

  final facade = bootstrapResult.facade!;
  if (enableCustomOverrides) {
    debugPrint(
      '[PhotoPipeline] overridesApplied: ${bootstrapResult.diagnostics['overridesApplied']}',
    );
  }

  runApp(
    ProviderScope(
      overrides: [
        pipelineFacadeProvider.overrideWithValue(facade),
      ],
      child: const CameraUploadApp(),
    ),
  );
}

/// 相机上传应用主类
class CameraUploadApp extends ConsumerWidget {
  const CameraUploadApp({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    // 触发流水线初始化（幂等），确保后续 Provider 可用。
    ref.watch(pipelineInitializationProvider);

    return MaterialApp(
      title: '相机连接传输',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        // 主色调
        primaryColor: AppColors.primary,
        scaffoldBackgroundColor: AppColors.background,
        brightness: Brightness.dark,

        // AppBar 主题（深色主题）
        appBarTheme: const AppBarTheme(
          backgroundColor: AppColors.background,
          foregroundColor: AppColors.textPrimary,
          elevation: 0,
          centerTitle: false,
          titleTextStyle: AppTextStyles.heading3,
          iconTheme: IconThemeData(
            color: AppColors.textPrimary,
          ),
        ),

        // 文本主题
        textTheme: const TextTheme(
          displayLarge: AppTextStyles.heading1,
          displayMedium: AppTextStyles.heading2,
          displaySmall: AppTextStyles.heading3,
          bodyLarge: AppTextStyles.body1,
          bodyMedium: AppTextStyles.body2,
          bodySmall: AppTextStyles.caption,
        ),

        // 卡片主题
        cardTheme: CardTheme(
          color: AppColors.cardBackground,
          elevation: 2,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12),
          ),
        ),

        // 分割线主题
        dividerTheme: const DividerThemeData(
          color: AppColors.divider,
          thickness: 1,
        ),

        // 图标主题
        iconTheme: const IconThemeData(
          color: AppColors.textPrimary,
          size: 24,
        ),

        // 按钮主题
        elevatedButtonTheme: ElevatedButtonThemeData(
          style: ElevatedButton.styleFrom(
            backgroundColor: AppColors.primary,
            foregroundColor: Colors.white,
            elevation: 2,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(12),
            ),
          ),
        ),

        // Material 3
        useMaterial3: true,
      ),

      // 路由配置
      initialRoute: '/home',
      routes: {
        '/home': (context) => const HomeScreen(),
        '/ai-settings': (context) => const AIPickSettingsScreen(),
        '/upload-tasks': (context) => const UploadTasksScreen(),
      },

      // 未找到路由时的处理
      onUnknownRoute: (settings) {
        return MaterialPageRoute(
          builder: (context) => const HomeScreen(),
        );
      },
    );
  }
}

BootstrapConfig _buildCustomBootstrapConfig() {
  return BootstrapConfig().registerOverride<UploadService>(
    () async => _ExampleUploadService(),
  );
}

class _ExampleUploadService implements UploadService {
  UploadStrategy _strategy = UploadStrategy.manual;
  final _strategyController = StreamController<UploadStrategy>.broadcast();

  @override
  Future<void> cancelUpload() async {
    debugPrint('[ExampleUploadService] cancelUpload');
  }

  @override
  Future<void> dispose() async {
    debugPrint('[ExampleUploadService] dispose');
    await _strategyController.close();
  }

  @override
  Future<void> initialize() async {
    debugPrint('[ExampleUploadService] initialize');
  }

  @override
  UploadProgress? get progress => null;

  @override
  Stream<UploadProgress> get progressStream => const Stream.empty();

  @override
  Stream<UploadStrategy> get uploadStrategyStream =>
      _strategyController.stream;

  @override
  Future<void> retryFailedUploads() async {
    debugPrint('[ExampleUploadService] retryFailedUploads');
  }

  @override
  UploadStrategy get uploadStrategy => _strategy;

  @override
  Future<void> uploadPhoto(int photoId) async {
    debugPrint('[ExampleUploadService] uploadPhoto($photoId)');
  }

  @override
  Future<void> uploadPhotos(List<int> photoIds) async {
    debugPrint('[ExampleUploadService] uploadPhotos($photoIds)');
  }

  @override
  void setUploadStrategy(UploadStrategy strategy) {
    _strategy = strategy;
    debugPrint('[ExampleUploadService] setUploadStrategy($strategy)');
    _strategyController.add(strategy);
  }
}
